import { GetUserInfo } from "@api/login.js"
import { setToken, setUsername, getUsername, removeToken, removeUsername } from "@api/app.js"

const app = {
    namespaced: true,

    state: {
        // nav的展开状态值isCollapse
        isCollapse: JSON.parse(sessionStorage.getItem('isCollapse')) || false,
        token: "",
        userame: getUsername() || ''
    },

    mutations: {
        // 在vuex中保存nav的展开状态值isCollapse
        setCollapse(state) {
            state.isCollapse = !state.isCollapse
                // html5本地存储
            sessionStorage.setItem('isCollapse', JSON.stringify(state.isCollapse))
        },

        // 将token写入vuex
        setToken(state, value) {
            state.token = value
        },

        // 将username写入vuex
        setUsername(state, value) {
            state.username = value
        }
    },

    actions: {
        login(context, requestData) {
            return GetUserInfo(requestData).then((response) => {
                if (response.access_token != '') {
                    console.log(response.access_token);
                    console.log("登录成功");

                    // token和username写入vuex
                    context.commit('setToken', response.access_token)
                    context.commit('setUsername', response.userName)

                    // token和username写入cookie
                    setToken(response.access_token)
                    setUsername(response.userName)

                    return Promise.resolve(response)
                } else {
                    console.log("登录失败");
                }
            }).catch((error) => {
                Promise.reject(error)
            })
        },

        exit(context) {
            // 清空vuex内token和username
            context.commit('setToken', "")
            context.commit('setUsername', "")

            // 清空cookie内token和username
            removeToken()
            removeUsername()

            return "退出系统"
        }
    }
}

export default app